<?php
/**
* @package		Joomla
* @subpackage	Search
* @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license		GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/

/* Check to ensure this file is included in Joomla! */
defined( '_JEXEC' ) or die( 'Restricted access' );

$mainframe->registerEvent( 'onSearch', 'botSearchJTags' );
$mainframe->registerEvent( 'onSearchAreas', 'botSearchJTagsAreas' );

/**
 * @return array An array of search areas
 */
function &botSearchJTagsAreas() {
	static $areas = array(
		'jtags' => 'Tags'
	);
	return $areas;
}

/**
* Tags Search method
*
* The sql must return the following fields that are used in a common display
* routine: href, title, section, created, text, browsernav
* @param string Target search string
* @param string matching option, exact|any|all
* @param string ordering option, newest|oldest|popular|alpha|category
*/
function botSearchJTags ($text, $phrase = '', $ordering = '', $areas = null)
{
	if (!$text) {
		return array();
	}

	if (is_array($areas)) {
		if (!array_intersect( $areas, array_keys( botSearchJTagsAreas() ) )) {
			return array();
		}
	}

	$plugin =& JPluginHelper::getPlugin('search', 'jtags');
 	$pluginParams = new JParameter( $plugin->params );

	$limit = $pluginParams->get( 'search_limit', 50 );

	$db =& JFactory::getDBO();

	if ($phrase == 'exact')
	{
		$where = "(LOWER(name) LIKE '%$text%')";
	}
	else
	{
		$words = explode( ' ', $text );
		$wheres = array();

		foreach ($words as $word) {
			$wheres[] = "(LOWER(name) LIKE '%$word%')";
		}

		if($phrase == 'all')
		{
			$separator = "AND";
		}
		else
		{
			$separator = "OR";
		}

		$where = '(' . implode( ") $separator (" , $wheres ) . ')';
	}

	switch ($ordering) {
		case 'oldest':
			$order = 'item_id ASC';
			break;

		case 'alpha':
			$order = 'title ASC';
			break;

		case 'popular':
			$order = 'hits DESC';
			break;

		case 'category':
			$order = 'catid ASC';
			break;

		case 'newest':
		default:
			$order = 'item_id DESC';
			break;
	}

	$query = "SELECT #__jtags_tags.tag_id, GROUP_CONCAT(name) AS name, title, introtext AS text, hits, catid," .
		"\n item_id, component," .
		"\n CONCAT('Matching tags: ', GROUP_CONCAT(name)) AS section," .
		"\n CONCAT('index.php?option=', component, '&view=article&id=', item_id) AS href," .
		"\n '2' AS browsernav" .
		"\n FROM #__jtags_items" .
		"\n NATURAL JOIN #__jtags_tags" .
		"\n JOIN #__content ON (#__jtags_items.item_id = #__content.id)" .
		"\n WHERE $where" .
		"\n GROUP BY item_id" .
		"\n ORDER BY $order";

	$db->setQuery( $query, 0, $limit );
	$rows = $db->loadObjectList();

	return $rows;
}

?>